package com.primaryedu.ui.exercise;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.adapter.ExerciseAdapter;
import com.primaryedu.bean.ExerciseBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.news.NewsActivity;
import com.primaryedu.widget.MyListView;
import com.primaryedu.widget.PullToRefreshView;
import com.primaryedu.widget.PullToRefreshView.OnFooterRefreshListener;
import com.primaryedu.widget.PullToRefreshView.OnHeaderRefreshListener;

/**
 * 活动
 *
 * @author jun.wang
 * @description
 * @data 2016年12月15日
 */
public class ExerciseActivity extends BaseActivity implements OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
    private MyListView myListView;
    ExerciseAdapter adapter;
    private List<ExerciseBean.DataBean.ListBean> newsLists;
    private boolean fistenter = true;
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != exerciseBean.getData().getList() && exerciseBean.getData().getList().size() != 0) {
                        if (newsLists == null) {
                            newsLists = exerciseBean.getData().getList();
                            adapter = new ExerciseAdapter(ExerciseActivity.this, newsLists);
                            myListView.setAdapter(adapter);
                        }else {
                            newsLists.addAll(exerciseBean.getData().getList());
                            adapter.notifyDataSetChanged();
                        }
                    }else {
                        if( newsLists!=null && newsLists.size()>0){
                            showToast( "亲，到底了");
                        }else{
                            showToast("亲，暂无数据");
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private PullToRefreshView pullToRefreshView;
    private int page = 1;

    private String columnId = "";
    private String titleStr = "";
    private ExerciseBean exerciseBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_exercise);

        columnId = getIntent().getStringExtra("columnId");
        titleStr = getIntent().getStringExtra("titleStr");
    }


    @Override
    protected int BindLayout() {
        return R.layout.activity_exercise;
    }

    @Override
    protected void initView() {
        ((TextView) findViewById(R.id.title)).setText(titleStr + "");
        findViewById(R.id.back).setOnClickListener(this);
        myListView = (MyListView) this.findViewById(R.id.listView);

        myListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                StringBuilder builder = new StringBuilder();
                builder.append(Contants.news_api);
                builder.append(newsLists.get(position).getId() + "/" + GlobalData.getUserId(ExerciseActivity.this));
                System.out.println("builder==" + builder.toString());
                Intent intent = new Intent(ExerciseActivity.this, NewsActivity.class);
                intent.putExtra("titleStr", newsLists.get(position).getTitle());
                intent.putExtra("urlStr", builder.toString());
                intent.putExtra("type", "1");
                intent.putExtra("newId", newsLists.get(position).getId());
                startActivity(intent);
            }
        });

        pullToRefreshView = (PullToRefreshView) this.findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    @Override
    protected void initData() {
        requestData(fistenter);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            default:
                break;
        }
    }

    private void requestData(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getNews,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response==Eexrcise" + response);
                        Gson gson = new Gson();
                        exerciseBean = gson.fromJson(response, ExerciseBean.class);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                /*String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                newsLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<NewsBean>>() {
                                        }.getType());
                                tempLists.addAll(newsLists);*/
                                handler.sendEmptyMessage(1001);
                                System.out.println("newsLists==" + newsLists);
                            }else {
                                showToast("数据获取失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                map.put("columnId", columnId);
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                page++;
                requestData(false);
                pullToRefreshView.onFooterRefreshComplete();
            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestData(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
            }

        }, 1500);
    }

}
